import { Row, Col, Form, Input, Button, Select, Card, Spin } from 'antd';
import { signin } from '@/services/auth';
import { useRequest, useNavigate, Link,useModel } from '@umijs/max'
import {decode} from 'jsonwebtoken';
import {useEffect} from 'react';
function SignIn() {
    const {initialState, setInitialState } = useModel('@@initialState');
    const navigate = useNavigate();
    const { loading, run } = useRequest(signin, {
        manual: true,//手工触发
        onSuccess(token) {//登录成功后处理
            //把服务器返回的token保存在本地
            localStorage.setItem('token',token);
            //因为用户名可有会出现在不同的组件中，所以需要把用户信息放在model里
            //这样的话所有的组件都可以共享和使用
            //我们使用jwt库解密token中的用户信息
            const currentUser = decode(token);
            //此操作是异步的，无法知道什么更新完成
            setInitialState({currentUser});
        }
    });
    useEffect(()=>{
        if(initialState.currentUser){
            navigate('/');
        }
    },[initialState])
    const onFinish = (values) => {
        run(values);//手工触发signup,进行真正的注册
    }
    return (
        <Row className='h-screen bg-gray-200' align='middle'>
            <Col offset={8} span={8}>
                <Card title="请登录" extra={<Link to="/signup">去注册</Link>}>
                    <Spin spinning={loading}>
                        <Form
                            onFinish={onFinish}
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}
                        >
                            <Form.Item
                                label="用户名"
                                name="username"
                                rules={[{ required: true, message: '请输入用户名' }]}>
                                <Input />
                            </Form.Item>
                            <Form.Item
                                label="密码"
                                name="password"
                                rules={[{ required: true, message: '请输入密码' }]}>
                                <Input />
                            </Form.Item>
                            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                                <Button type="primary" htmlType="submit">提交</Button>
                            </Form.Item>
                        </Form>
                    </Spin>
                </Card>
            </Col>
        </Row>
    )
}

export default SignIn;